<template>
  <div>
    <div class="votes" v-if="type === 0">
      <!-- 买入REX / 抵押CPU、NET -->
      <div v-if="!status">
        <div class="votesList">
          <div class="listLeft pt10">{{ $t('newpos.miningMethod') }}</div>
          <div class="listRight">
            <div v-for="(item, index) in activeList"
              :key="index"
              class="tab"
              :class="{'active': index === active}"
              @click="handleChangeActive(index)"
              >
              {{ item.label }}
              <i v-if="!active && !item.value"
                class="iconfont icon"
                :class="`icon-max-${$store.state.app.language}`"
                :style="$store.state.app.language === 'en' ? 'top: -31px; right: -14px;' : ''"></i>
            </div>
          </div>
        </div>
        <div class="backblue">
          <div class="votesList">
            <!-- 节点收益 -->
            <div class="listLeft pbx" :class="{'enClass': $store.state.app.language === 'en'}">{{ $t('newpos.bpIncome') }}</div>
            <div class="listRight rexProfit clearfix" :style="$store.state.app.language === 'en' ? 'padding-right:3px;' : ''">
              <span class="goldColor">{{ $t('newpos.nodeYearBenefits') }} {{detInfo.maxNodeAnnualizedRate || '0.00'}}%</span>
            </div>
            <!-- REX收益 -->
            <div class="listLeft pbx" :class="{'enClass': $store.state.app.language === 'en'}">{{ $t('newpos.rexProfits') }}</div>
            <div class="listRight rexProfit clearfix" :style="$store.state.app.language === 'en' ? 'padding-right:3px;' : ''">
              <template v-if="!active">
                <span class="goldColor">{{ $t('newpos.yesterdayEarnings') }} {{detInfo.maxRexAnnualizedRate || '0.00'}}%</span>
              </template>
              <template v-else>
                <span class="none">{{ $t('ndxStake.none') }}</span>
              </template>
              <p class="shareTip" v-if="!active">({{ $t('newpos.enjoyBpIncome') }})</p>
            </div>
          </div>
          <div class="votesList rules">
            <!-- 退出规则 -->
            <div class="listLeft" :class="{'enClass': $store.state.app.language === 'en'}">{{ $t('newpos.exitRule') }}</div>
            <div class="listRight">
              <template v-if="!active">
                <p>{{ $t('newpos.accordingRexRule') }}</p>
                <p>{{ $t('newpos.sellAfter') }}{{(handleDateReturn())}} 08:00{{ $t('newpos.sellAfter1') }}</p>
                <p>{{ $t('newpos.sellAfter2') }}</p>
                <a class="mr fr color999 hoverBlue"
                  :href="handleRexHref('rex')"
                  target="_blank">{{ $t('newpos.whatIsRex') }}</a>
              </template>
              <template v-else>
                <p>{{ $t('newpos.accordingCpuNetRule') }}</p>
                <p>{{ $t('newpos.cpuNetTip') }}</p>
                <p>{{ $t('newpos.cpuNetTip1') }}</p>
                <a class="mr fr color999 hoverBlue"
                  :href="handleRexHref('cpu')"
                  target="_blank">{{ $t('newpos.whatIsCpnNet') }}</a>
              </template>
            </div>
          </div>
        </div>
        <div class="votesList exitVotes">
          <!-- 已有REX/已抵押 -->
          <div v-if="!active">
            <rex-balance
              :rexBalance="rexBalance"
              :rexTableRows="rexTableRows" />
          </div>
          <div v-else>
            <div class="listLeft">
              <div>{{ $t('newpos.staked') }}</div>
              <div class="color999 pt5">({{ $t('newpos.numberOfVotes') }})</div>
            </div>
            <div class="listRight">
              <div class="pb5">CPU：{{cpuWeightAll}} EOS</div>
              <div>
                <span class="mr">NET：{{netWeightAll}} EOS</span>
                <span class="color999">1 EOS = 1 {{ $t('newpos.ticket') }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="votesList exitVotes buyMore">
          <!-- 买入更多/抵押更多 -->
          <div class="listLeft">
            <div v-if="!active">{{ $t('newpos.buyMore') }}</div>
            <div v-else>{{ $t('newpos.stakedMore') }}</div>
            <div class="color999 pt5">（{{ $t('newpos.additionalVotes') }})</div>
          </div>
          <div class="listRight">
            <!-- rex输入框 -->
            <template v-if="!active">
              <el-input type="number"
              v-model="inputRex"
              clearable
              step="0.0001"
              min="0.0001"
              :placeholder="$t('newpos.pleaseEnterQuantity')">
                <span slot="suffix" class="suffixSlot">EOS</span>
              </el-input>
            </template>
            <div class="cpuInput" v-else>
              <!-- 账户输入框 -->
              <el-input type="text"
              clearable
              v-model="receiver" :placeholder="$t('newpos.pleaseEnterStakeAccount')" class="mb">
                <template slot="prepend">{{ $t('newpos.receiveAccount') }}</template>
              </el-input>
              <!-- cpu输入框 -->
              <el-input type="number"
              clearable
              step="0.0001"
              min="0.0001"
              v-model="inputCpu" :placeholder="$t('newpos.pleaseEnterQuantity')" class="mb">
                <template slot="prepend">CPU</template>
                <span slot="suffix" class="suffixSlot">EOS</span>
              </el-input>
              <!-- net输入框 -->
              <el-input type="number"
              clearable
              step="0.0001"
              min="0.0001"
              v-model="inputNet" :placeholder="$t('newpos.pleaseEnterQuantity')">
                <template slot="prepend">NET</template>
                <span slot="suffix" class="suffixSlot">EOS</span>
              </el-input>
            </div>
          </div>
        </div>
        <!-- 余额 -->
        <div class="balance right color999" @click="inputRex = parseFloat(eosBalance)" style="cursor: pointer;">
          <span>{{ $t('myWallet.balance') }}：{{eosBalance}}</span>
        </div>
        <!-- 确定按钮 -->
        <div class="votesBtn"
        v-loading="loading"
        @click="handleAction"> {{ $t('public.sure') }} </div>
        <div class="center color999">{{ $t('newpos.votesLayerTip1') }}</div>
        <div class="tip center">{{ $t('newpos.votesLayerTip2') }}</div>
      </div>
      <!-- 卖出REX / 赎回CPU、NET -->
      <div v-else>
        <!-- 减少方式 -->
        <div class="votesList">
          <div class="listLeft pt10">{{ $t('newpos.reduceType') }}</div>
          <div class="listRight">
            <div v-for="(item, index) in activeReduceList"
              :key="index"
              class="tab"
              :class="{'active': index === active}"
              @click="handleChangeActive(index)"
              >{{ item.label }}</div>
          </div>
        </div>
        <!-- 到账时间 -->
        <div class="backblue">
          <div class="votesList">
            <div class="listLeft">{{ $t('newpos.paymentDate') }}</div>
            <div class="listRight">
              <template  v-if="!active">
                <span>{{ $t('newpos.realtimeArrival') }}</span>
              </template>
              <template v-else>
                <p>{{ $t('newpos.accordingCpuNetRule') }}</p>
                <p>{{ $t('newpos.arriveInThreeDays') }}</p>
              </template>
            </div>
          </div>
        </div>
        <div class="votesList exitVotes">
          <div v-if="!active">
            <!-- 已有REX -->
            <rex-balance
              :rexBalance="rexBalance"
              :rexTableRows="rexTableRows" />
          </div>
          <div v-else>
            <!-- 已抵押 -->
            <div class="listLeft pt0">
              <div>{{ $t('newpos.staked') }}</div>
              <div class="color999 pt5">({{ $t('newpos.numberOfVotes') }})</div>
            </div>
            <div class="listRight staked">
              <span v-if="receiverList.length === 0">{{receiver}}</span>
              <template v-else>
                <span class="accountRight">{{ $t('order.account') }}</span>
                <el-select v-model="receiver" class="selectWidth"
                @change="handleChangeReceiver"
                size="small"
                style="width: 160px;margin-right:13px;">
                  <el-option style="font-size: 12px;"
                    v-for="item in receiverList"
                    :key="item.to"
                    :label="item.to"
                    :value="item.to">
                  </el-option>
                </el-select>
              </template>
              <div class="mt" @click="inputCpu = parseFloat(cpuWeight)"
              :class="{pl40 : receiverList.length !== 0}">CPU：{{cpuWeight}}</div>
              <div class="mt5">
                <div class="mr" @click="inputNet = parseFloat(netWeight)"
                :class="{pl40 : receiverList.length !== 0}">
                  NET：{{netWeight}}
                  <!-- <span class="color999 ml10">1 EOS = 1 {{ $t('newpos.ticket') }}</span> -->
                </div>
                <!-- <div class="color999 mt5">1 EOS = 1 {{ $t('newpos.ticket') }}</div> -->
              </div>
            </div>
          </div>
        </div>
        <!-- 可卖出 -->
        <div class="votesList exitVotes" style="border:none; padding-bottom: 0;" v-if="!active">
          <div class="listLeft">{{ $t('newpos.canSell') }}</div>
          <div class="listRight clearfix" style="line-height: 22px;">
            <span class="mr fl" @click="inputRex = parseFloat(canBuyRexNum)">{{canBuyRexNum}}</span>
            <!-- 待解锁 -->
            <span class="colorBlue fr" @click="sellDetailsVisible = true;">{{ $t('newpos.toBeUnlocked') }}</span>
          </div>
        </div>
        <div class="votesList exitVotes buyMore">
          <!-- 卖出REX/赎回数量 -->
          <div class="listLeft pt0">
            <div v-if="!active">{{ $t('newpos.sellRex') }}</div>
            <div v-else>{{ $t('newpos.RedemptionQuantity') }}</div>
            <div class="color999 pt5">（{{ $t('newpos.reduceVotes') }}）</div>
          </div>
          <div class="listRight">
            <!-- 卖出REX -->
            <template v-if="!active">
              <el-input type="number"
              clearable
              step="0.0001"
              min="0.0001"
              v-model="inputRex" :placeholder="$t('newpos.pleaseEnterQuantity')">
                <span slot="suffix" class="suffixSlot">REX</span>
              </el-input>
              <span class="fr mt5">≈{{toFixed(toNonExponential(inputRex * rexTableRows.rexPrice), 4)}} EOS</span>
            </template>
            <!-- 赎回数量 -->
            <div class="cpuInput" v-else>
              <el-input type="number"
              clearable
              step="0.0001"
              min="0.0001"
              v-model="inputCpu" :placeholder="$t('newpos.pleaseEnterQuantity')" class="mb">
                <template slot="prepend">CPU</template>
                <span slot="suffix" class="suffixSlot">EOS</span>
              </el-input>
              <el-input type="number"
              clearable
              step="0.0001"
              min="0.0001"
              v-model="inputNet" :placeholder="$t('newpos.pleaseEnterQuantity')">
                <template slot="prepend">NET</template>
                <span slot="suffix" class="suffixSlot">EOS</span>
              </el-input>
            </div>
          </div>
        </div>
        <!-- 确定按钮 -->
        <div class="votesBtn"
        v-loading="loading"
        @click="handleAction"> {{ $t('public.sure') }} </div>
      </div>
      <!-- 卖出REX明细 -->
      <el-dialog
        :title="`${$t('newpos.toBeUnlocked')} REX`"
        class="votesDiaog"
        :modal="false"
        :close-on-click-modal="false"
        :visible.sync="sellDetailsVisible"
        width="700px">
        <sell-Details @listenSellDetails="handleSellDetails" :sellDetailsVisible="sellDetailsVisible"/>
      </el-dialog>
    </div>
    <div v-else>
      <!-- 减少挖矿/增加挖矿成功页面 -->
      <result-page @listenResult="handleResult" :resultVisible="resultVisible" :type="type"/>
    </div>
  </div>

</template>

<script>
import moment from 'moment';
import axios from 'axios';
import { EosModel } from '@/utils/eos';
import { toFixed, toNonExponential } from '@/utils/validate';
import SellDetails from './SellDetails';
import ResultPage from './ResultPage';

const RexBalance = {
  props: {
    rexBalance: String,
    rexTableRows: Object,
  },
  template: `<div :class="{'blackStyle': $store.state.app.theme === 'theme-1B1D27'}">
    <div class="listLeft pt0">
      <div class="comRex">{{ $t('newpos.existingRex') }}</div>
      <div class="color999 pt5">({{ $t('newpos.numberOfVotes') }})</div>
    </div>
    <div class="listRight">
      <div>
        <div>{{rexBalance}}</div>
        <div class="pt5" v-if="rexTableRows">
          <span class="mr color999">≈{{(rexTableRows.rexPrice * parseFloat(rexBalance, 0)).toFixed(4)}} EOS</span>
          <span class="color999">1 EOS = 1 {{ $t('newpos.ticket') }}</span>
        </div>
      </div>
    </div>
  </div>`,

};
export default {
  name: 'votes', // 投票页面
  data() {
    return {
      loading: false,
      active: 0,
      activeList: [
        {
          value: 0,
          label: this.$t('newpos.buyRex'),
        },
        {
          value: 1,
          label: this.$t('newpos.stakedCpuNet'),
        }
      ],
      activeReduceList: [
        {
          value: 0,
          label: this.$t('newpos.sellRex'),
        },
        {
          value: 1,
          label: this.$t('newpos.redeemCpuNet'),
        }
      ],
      inputRex: null,
      inputCpu: null,
      inputNet: null,
      sellDetailsVisible: false, // 卖出明细
      resultVisible: false, // 结果页面
      rexHistroyList: [], // rex 解锁明细
      rexTableRows: {}, // rex 全网数据

      receiver: '', // 赎回/抵押 账号
      cpuWeight: '0.0000', // 当前账号的 cpu 抵押数量
      netWeight: '0.0000', // 当前账号的 net 抵押数量
      cpuWeightAll: '0.0000', // 所有账号 cpu 抵押数量
      netWeightAll: '0.0000', // 所有账号 net 抵押数量
      language: '',
      receiverList: [],
      type: 0, // 结果页面状态值 1-rex赎回 2-cpu/net赎回 3-挖矿成功
    }
  },
  components: {
    SellDetails,
    RexBalance,
    ResultPage,
  },
  props: {
    scatter: Object,
    votesVisible: {
      type: Boolean,
      default: false
    },
    status: { // 1-减少挖矿，0-挖矿增加
      type: Number,
      default: 0,
    },
    proxyList: Array, // 所有的代理节点名称
    eosBalance: String,
    rexBalance: String,
    canBuyRexNum: String, // rex 可卖
    env: String, // 环境变量
    detInfo: Object,
  },
  watch: {
    '$store.state.app.language': function change(val) {
      this.language = val;
      this.activeList = [
        {
          value: 0,
          label: this.$t('newpos.buyRex'),
        },
        {
          value: 1,
          label: this.$t('newpos.stakedCpuNet'),
        }
      ];
      this.activeReduceList = [
        {
          value: 0,
          label: this.$t('newpos.sellRex'),
        },
        {
          value: 1,
          label: this.$t('newpos.redeemCpuNet'),
        }
      ];
    },
    votesVisible: function change(val) {
      this.loading = false;
      setTimeout(() => {
        this.type = 0; // 结果页面状态值 1-rex赎回 2-cpu/net赎回 3-挖矿成功
      }, 500);
      if (val) {
        this.active = 0;
        this.handleMounted();
      }
    },
  },
  computed: {},
  created() {},
  mounted() {
    this.language = this.$store.state.app.language;
    this.handleMounted();
  },
  beforeDestroy() {},
  methods: {
    // REX 介绍
    handleRexHref(val) {
      const url = {
        rex: {
          'zh-CN': 'https://newdex.zendesk.com/hc/zh-cn/articles/360028013572-REX-%E7%BB%88%E6%9E%81%E6%8C%87%E5%8D%97',
          'zh-TW': 'https://newdex.zendesk.com/hc/zh-tw/articles/360028013572-REX%E7%B5%82%E6%A5%B5%E6%8C%87%E5%8D%97',
          en: 'https://newdex.zendesk.com/hc/en-us/articles/360028013572-REX-Instructions',
          ko: 'https://newdex.zendesk.com/hc/ko/articles/360028013572-REX-Instruction',
        },
        cpu: {
          'zh-CN': 'https://newdex.zendesk.com/hc/zh-cn/articles/360029339611-%E4%BB%80%E4%B9%88%E6%98%AFEOS%E8%B5%84%E6%BA%90',
          'zh-TW': 'https://newdex.zendesk.com/hc/zh-tw/articles/360029339611-%E4%BB%80%E9%BA%BC%E6%98%AFEOS%E8%B3%87%E6%BA%90',
          en: 'https://newdex.zendesk.com/hc/en-us/articles/360029339611-What-Is-EOS-Resources-',
          ko: 'https://newdex.zendesk.com/hc/ko/articles/360029339611-EOS-%EC%9E%90%EC%9B%90%EC%9D%B4%EB%9E%80-',
        }
      }
      return url[val][this.language];
    },
    // mounted action
    handleMounted() {
      this.accountName = this.$store.state.app.scatter.identity.accounts[0].name;
      this.inputRex = null;
      this.inputCpu = null;
      this.inputNet = null;
      this.cpuWeight = '0.0000'; // 当前账号的 cpu 抵押数量
      this.netWeight = '0.0000'; // 当前账号的 net 抵押数量
      this.cpuWeightAll = '0.0000'; // 所有账号 cpu 抵押数量
      this.netWeightAll = '0.0000'; // 所有账号 net 抵押数量
      this.handleGetRexTableRow();
      // 获取抵押资源CPU/NET
      this.handleGetTableRowsForStaket();
    },
    // 确定操作
    handleAction() {
      if (this.loading) return;
      const status = this.status; // 0-减少挖矿，1-挖矿增加
      const active = this.active;
      this.inputRex = Number(toFixed(this.inputRex, 4)) || 0;
      this.inputCpu = Number(toFixed(this.inputCpu, 4)) || 0;
      this.inputNet = Number(toFixed(this.inputNet, 4)) || 0;
      const inputRex = this.inputRex || 0;
      const inputCpu = this.inputCpu || 0;
      const inputNet = this.inputNet || 0;
      const expectSell = this.inputRex * this.rexTableRows.rexPrice; // 卖出REX大约得到的EOS
      const inputRexFormat = toFixed(inputRex, 4);
      const inputCpuFormat = toFixed(inputCpu, 4);
      const inputNetFormat = toFixed(inputNet, 4);
      const expectSellFormat = toFixed(toNonExponential(expectSell), 4);
      const stakeCount = active === 0 && status === 0 ? inputRex : (inputCpu + inputNet);
      this.handleGetProxy({ stakeCount }).then((proxyResponse) => {
        const rexProxy = proxyResponse || 'newdexproxy1';
        // 获取用户现有的代理账号
        const voterInfo = this.$store.state.app.accountRes;
        const proxyNow = voterInfo.proxy;
        if (active === 0) { // REX操作
          if (isNaN(inputRex) || inputRex < 0.0001) { // 请输入正确的数量
            this.$message.error(`${this.$t('public.inputRightNum')} ≥ 0.0001`);
            return;
          }
          const params = {
            proxy: rexProxy, // 投票的节点名称
            getEos: `${expectSellFormat} ${this.env}`
          };
          if (status === 1) { // 卖出REX
            if (inputRex > parseFloat(this.canBuyRexNum)) {
              this.$message.error(this.$t('jy.error3')); // 余额不足
              return;
            }
            this.loading = true;
            params.hasResources = 1;
            params.action = 'sellrex';
            params.rex = `${inputRexFormat} REX`;
            this.handleRexModelAction(params, proxyNow);
            return;
          }
          if (status === 0) { // 买入REX
            if (inputRex > parseFloat(this.eosBalance)) {
              this.$message.error(this.$t('jy.error3')); // 余额不足
              return;
            }
            this.loading = true;
            params.action = 'buyrex';
            params.amount = `${inputRexFormat} ${this.env}`;
            params.hasResources = 0;
            const dqAccount = this.scatter.identity.accounts[0].name;
            const getdq = this.receiverList.find(v => v.to === dqAccount);
            if (getdq) {
              const addCpuNet = parseFloat(getdq.cpu_weight, 0) + parseFloat(getdq.net_weight, 0)
              params.hasResources = addCpuNet > 0 ? 1 : 0; // 如果没有给自己抵押资源的
            }
            this.handleRexModelAction(params, proxyNow);
            return
          }
          return;
        }
        if (active === 1) { // CPU/NET 操作
          const cpuWeight = parseFloat(this.cpuWeight, 0);
          const netWeight = parseFloat(this.netWeight, 0);
          if ((inputCpu && (isNaN(inputCpu) || inputCpu < 0.0001))
          || (inputNet && (isNaN(inputNet) || inputNet < 0.0001))) { // 请输入正确的数量
            this.$message.error(`${this.$t('public.inputRightNum')} ≥ 0.0001`);
            return;
          }
          if (status === 1) { // 赎回CPU/NET
            if (!inputCpu && !inputNet) {
              this.inputNet = null;
              this.inputCpu = null;
              this.$message.error(this.$t('rex.redeemOneResource'));
              return;
            }
            if (inputCpu > cpuWeight) {
              this.$message.error(this.$t('rex.exceedStakedNum', { type: 'CPU' }));
              return;
            }
            if (inputNet > netWeight) {
              this.$message.error(this.$t('rex.exceedStakedNum', { type: 'NET' }));
              return;
            }
            this.loading = true;
            const params = {
              proxy: rexProxy, // 投票的节点名称
              receiver: this.receiver, // 抵押账户
              cpu_quantity: `${inputCpuFormat} ${this.env}`,
              net_quantity: `${inputNetFormat} ${this.env}`,
              way: 'newpos',
              type: status // 0 抵押 1赎回
            };
            this.handleCpuNetModelAction(params, proxyNow)
            return;
          }
          if (status === 0) { // 抵押CPU/NET
            if (!this.receiver) {
              this.$message.error(this.$t('newpos.pleaseEnterMortgageAccount')); // 请输入抵押账户名
              return;
            }
            // 该账户是否存在
            this.handleValidateReceive().then((hasEosAccount) => {
              if (!hasEosAccount) {
                this.$message.error(this.$t('bosChain.accountNone', { chain: 'EOS' })); // 该账户不存在
                return;
              }
              if (!inputCpu && !inputNet) {
                this.inputNet = null;
                this.inputCpu = null;
                this.$message.error(this.$t('newpos.MortgageLeastOneResource'));
                return;
              }
              if ((inputCpu + inputNet) > parseFloat(this.eosBalance)) {
                this.$message.error(this.$t('jy.error3')); // 余额不足
                return;
              }
              this.loading = true;
              const params = {
                proxy: rexProxy, // 投票的节点名称
                cpu_quantity: `${inputCpuFormat} ${this.env}`,
                net_quantity: `${inputNetFormat} ${this.env}`,
                transfer: 0,
                receiver: this.receiver,
                way: 'newpos',
                type: status // 0 抵押 1赎回
              };
              this.handleCpuNetModelAction(params, proxyNow)
            })
          }
        }
      })
    },
    // rex model Action
    handleRexModelAction(obj, proxyNow) {
      const params = obj;
      params.way = 'newpos';
      // 是否已投我们的代理
      if (this.proxyList.find(v => v === proxyNow)) {
        params.proxy = proxyNow;
      }
      EosModel.rexTransaction(params, (res) => {
        this.loading = false;
        if (res.processed) {
          // this.$message.success(this.$t('newpos.successfulOperation'));
          // setTimeout(() => {
          if (params.action === 'sellrex') {
            this.type = 1;
          } else {
            this.type = 3;
          }
          this.handleResetLocal();
          this.handleMounted();
          this.$emit('listenVotes', 'back')
          this.resultVisible = true;
          // }, 1000);
          return
        }
        EosModel.handleScatterErrorBack(res);
      });
    },
    // cpu/net model Action
    handleCpuNetModelAction(obj, proxyNow) {
      const params = obj;
      params.way = 'newpos';
      // 是否已投我们的代理
      if (this.proxyList.find(v => v === proxyNow)) {
        params.proxy = proxyNow;
      }
      EosModel.CpuNetTransaction(params, (res) => {
        this.loading = false;
        if (res.processed) { // 抵押成功
          this.handleMounted();
          // this.$message.success(this.$t('newpos.successfulOperation'));
          this.inputNet = null;
          this.inputCpu = null;
          if (params.type === 1) {
            this.type = 2;
          }
          if (params.type === 0) {
            this.type = 3;
          }
          this.handleResetLocal();
          this.$emit('listenVotes', 'back')
          this.resultVisible = true;
          return
        }
        EosModel.handleScatterErrorBack(res);
      });
    },
    // 获取rex全网信息
    handleGetRexTableRow() {
      EosModel.getRexTableRows((row) => {
        if (row.code) return;
        // namebid_proceeds: "0.0000 EOS"
        // total_lendable: "56668081.1690 EOS"   总量
        // total_lent: "1372018.5243 EOS"   已出租
        // total_rent: "20824.1210 EOS"   -20000，租金
        // total_rex: "566563921265.5349 REX"  总量
        // total_unlent: "55296062.6447 EOS"   剩余可出租
        // version: 0
        this.rexTableRows = row;
        // 年化收益率 计算
        const since = Date.now() - moment('2019-05-01 20:00:00').format('x');
        const n = ((parseFloat(row.total_lendable, 0) / parseFloat(row.total_rex, 0)) - 0.0001) / 0.0001;
        const apr = parseFloat((n / since) * 365 * 24 * 3600 * 1000 * 100).toFixed(2);
        this.rexTableRows.apr = apr;
        const pr = parseFloat(row.total_lendable, 0) / parseFloat(row.total_rex, 0);
        this.rexTableRows.rexPrice = toNonExponential(pr);
      })
    },
    // 获取抵押账户
    handleGetTableRowsForStaket() {
      this.receiver = this.scatter.identity.accounts[0].name;
      EosModel.getTableRowsForStaket((res) => {
        this.receiverList = res.rows;
        if (this.receiverList && this.receiverList.length === 0) {
          this.cpuWeight = '0.0000 EOS'; // cpu 抵押数量
          this.netWeight = '0.0000 EOS'; // net 抵押数量
          return;
        }
        let cpuWeightAll = 0;
        let netWeightAll = 0;
        this.receiverList.forEach((v) => {
          cpuWeightAll += parseFloat(v.cpu_weight, 0);
          netWeightAll += parseFloat(v.net_weight, 0);
        })
        this.cpuWeightAll = toFixed(cpuWeightAll, 4);
        this.netWeightAll = toFixed(netWeightAll, 4);
        this.handleChangeReceiver()
      })
    },
    // 选择抵押账户
    handleChangeReceiver() {
      const to = this.receiver;
      const val = this.receiverList.find(v => v.to === to);
      if (val) {
        this.cpuWeight = val.cpu_weight || '0.0000 EOS';
        this.netWeight = val.net_weight || '0.0000 EOS';
      }
    },
    // tab 切换
    handleChangeActive(index) {
      this.active = index;
      this.inputRex = null;
      this.inputCpu = null;
      this.inputNet = null;
    },
    // 明细回调
    handleSellDetails() {
    },
    // 获取投票代理账号
    async handleGetProxy(params) {
      let back = 'newdexproxy1';
      back = await this.$http.post('/pool/getProxy', params).then((res) => {
        if (res.code !== 0) {
          // const msg = res.msg || 'System error'
          // this.$message.error(msg);
          return 'newdexproxy1';
        }
        return res.proxy
      });
      return back
    },
    // 验证账户是否存在
    async handleValidateReceive() {
      const nodeChecked = this.$store.state.app.nodeChecked;
      const nodeobj = nodeChecked.eos;
      const kip = nodeobj.url;
      const accountParams = {
        account_name: this.receiver
      };
      const back = await axios.post(`${kip}/v1/chain/get_account`, JSON.stringify(accountParams)).then((result) => {
        if (result.status !== 200) return false;
        return true;
      }).catch(() => false);
      return back;
    },
    // 把本地存储衰退记录置为空
    handleResetLocal() {
      const attenuationLocal = JSON.parse(localStorage.getItem('attenuationDialog') || '{}');
      attenuationLocal[this.accountName] = null;
      localStorage.setItem('attenuationDialog', JSON.stringify(attenuationLocal));
    },
    handleDateReturn() {
      return moment.utc().add(5, 'd').format('YYYY-MM-DD')
    },
    // 结果页回调
    handleResult() {
    },
    // 数字截取 - 保留小数
    toFixed(num, p) {
      if (!num && num !== 0) {
        return toFixed(0, p);
      }
      return toFixed(num, p);
    },
    toNonExponential(num) {
      return toNonExponential(num)
    }
  },
}
</script>
<style lang="scss" scoped>
@import '@/views/newpos/public.scss';
.goldColor {
  color: #964D05 !important;
}
.pl40 {
  padding-left: 40px;
}
.votes{
  padding: 0 40px;

  .hoverBlue:hover {
    color: #278EDA !important;
  }

  .votesList {
    /deep/ .listLeft {
      display: inline-block;
      width: 30%;
      text-align: center;
      vertical-align: top;
    }

    /deep/ .listRight {
      display: inline-block;
      width: 68%;

      .shareTip {
        color: #999;
        margin: 5px 0 10px;
      }

      .tab {
        position: relative;
        display: inline-block;
        width: 140px;
        line-height: 40px;
        color: #333;
        border: 1px solid #e4e7ed;
        text-align: center;
        border-radius: 4px;
        cursor: pointer;
      }

      .tab:first-child {
        margin-right: 15px;
      }

      .active {
        background: #FFC78A;
        color: #964D05;
        border-color: #FFC78A;
      }

      .icon {
        position: absolute;
        top: -31px;
        right: -10px;
        font-size: 24px;
        color: red;
        z-index: 100;
      }
    }
  }

  .backblue {
    background: rgba(154, 178, 237, 0.22);
    border-radius: 8px;
    padding: 20px 0 20px 0;
    margin-top: 20px;

    .enClass {
      text-align: right;
      padding-right: 20px;
    }

    .rules {
      .listLeft {
        vertical-align: top;
      }
    }

    .rexProfit {
      padding-right: 15px;
      color: #964D05;

      span:nth-child(1) {
        color: #666;
      }
    }
  }

  .exitVotes {
    padding: 20px 0;
    border-bottom: 1px solid #e4e7ed;

    .listLeft {
      // line-height: 24px;
    }

    input {
      height: 30px;
    }
  }

  .buyMore {
    border: none;
    padding-bottom: 10px;
  }

  /deep/ .el-input-group__prepend {
    text-align: center;
    width: 110px;
    padding: 0;
  }

  .votesBtn {
    text-align: center;
    line-height: 45px;
    background: #FFC78A;
    color: #964D05;
    border-radius: 4px;
    margin: 20px 0;
    cursor: pointer;
    font-size: 16px;
  }

  .tip {
    margin-top: 5px;
    color: #CC7323;
  }

  .accountRight {
    display: inline-block;
    line-height: 40px;
    height: 40px;
    width: 110px;
    text-align: center;
    color: #999;
    background: #f5f7fa;
    border: 1px solid rgb(220, 223, 230);
    margin-right: -5px;
    border-right: none;
    margin-bottom: 3px;
    vertical-align: middle;
    border-top-left-radius: 4px !important;
    border-bottom-left-radius: 4px !important;
  }

  .selectWidth {
    &.el-select {
      width: 201px !important;
      margin-right: 0 !important;
    }

    /deep/ .el-input {
      width: 202px;
      line-height: 40px;
      margin-top: 1px;
    }
    /deep/ input {
      width: 202px;
      height: 40px;
      border-top-left-radius: 0px !important;
      border-bottom-left-radius: 0px !important;
    }
  }
}

/deep/ .el-input__inner {
  padding-right: 40px;
}

.suffixSlot {
  display: inline-block;
  vertical-align: middle;
  height: 40px;
  line-height: 40px;
}

.theme-1B1D27 {
  .icon {
    color: #FFC78A !important;
  }
  .shareTip {
    color: #fff !important;
  }
  .exitVotes {
    border-color: $borderColor;
  }
  .rexProfit {
    .none {
      color: #fff !important;
    }

    a {
      color: #FFC78A !important;
    }
  }

  .tip {
    color: #FFC78A !important;
  }

  .color999 {
    color: $colorBlue !important;
  }

  .listLeft {
    color: #fff !important;

    .color999 {
      color: $colorBlue !important;
    }
  }

  .balance {
    color: $colorBlue !important;
  }

  .listRight {
    color: #fff;

    .tab {
      color: $colorBlue !important;
      border-color: $colorBlue !important;

      &.active {
        color: #964D05 !important;
      }
    }

    .goldColor {
      color: #FFC78A !important;
    }
  }
}

/deep/ .blackStyle {
  .comRex {
    color: #fff !important;
  }

  .color999 {
    color: $colorBlue !important;
  }

  .listRight {
    color: #fff !important;
  }
}
</style>
